<?php
$loader->requireOnce('includes/RegistrationInfo.class.php');
/**
 * controll the registration pation process
 *
 *
 */

class PatientRegistration {
    private $_db;
    
    function __construct() {
        $this->_db  =  Celini::dbInstance();
    }
    
    /**
     *
     * Register patient information into system.
     * return patient id if succesful
     *
     * @param $registrationInfoObj RegistrationInfo instant of class RegistrationInfo
     * @return $result = array('code'=>'', 'id'=>'');
     * code : patient code
     * id : patient id
     */
    public function registerPatientInfo($registrationInfoObj) {
        
        $result = array('code'=>'', 'id'=>'');
        $patientId = $registrationInfoObj->getPatientId();
        if (empty($patientId)) {
            //addnew

            // Add address first to get address_id
            $addressObj =& ORDataObject::factory('Address');
            $addressObj->populateArray($registrationInfoObj->getPersonAddressData());
            $addressObj->persist();
                        
            // Then add person to get person_id & add patient
            $personData = $registrationInfoObj->getPersonData();
            $personData['address_id'] = $addressObj->get_id();
            $person =& ORDataObject::factory('Person');
            $person->populateArray($personData);
            $person->persist();
            
            //add patient
            $patientData = $registrationInfoObj->getPatientData();
            $patientData['patient_code'] = Celini::newOrdo('Patient')->genCode();
            $patient =& ORDataObject::factory('Patient');
            $patientId = $person->getId();
            $patientData['person_id'] =  $patientId;
            
            $patient->populateArray($patientData);
            $patient->persist();
            
            $result['code'] = $patientData['patient_code'];
            $result['id'] = $patient->get_id();

            $this->saveInsurance($registrationInfoObj, $patient->get_id());
        } else {
            // Person
            $person = ORDataObject::factory('Person', $registrationInfoObj->getPatientId());
            $persontData = $registrationInfoObj->getPersonData();
            $person->populateArray($persontData);
            $person->persist();
            
            //address
            $address = ORDataObject::factory('Address', $person->get('address_id'));
            $address->populateArray($registrationInfoObj->getPersonAddressData());
            $address->persist();

            // patient
            $patient = ORDataObject::factory('Patient', $registrationInfoObj->getPatientId());
            $patient->populateArray($registrationInfoObj->getPatientData());
            $patient->persist();
                        
            $result['code'] = $patient->get('patient_code');
            $result['id'] = $patient->get_id();
            
            $this->saveInsurance($registrationInfoObj, $patient->get_id());
        }
        return $result;
    }
    
    
    /**
     * Register patient for examination
     * @param $patientId
     * @param $departmentId
     * @param $insurance 0,1
     *      1   insurance patient admissison
     *      0   service patient admission
     * @return array(ticket_id, medical_record_id) : id of treatment duration be registered to
     **/
    public function registerTreatment($patientId, $departmentId, $insurance) {
        
        $result = array('ticketId'=>'', 'recordId' => '');
        $ticketObj = Celini::newORDO('Ticket');
        $medicalRecordObj = Celini::newOrdo('MedicalRecord');
        $today = date('Y-m-d');
        
        
        
        if ($insurance == 1) {
            // Patient had ticket on today, and the ticket HAS insurance info
            // Reuse the ticket
            $examType = EnumerationConstant::EXAMINATION_TYPE_INSURANCE_KEY;
            $res = $ticketObj->getLatestTicketByDate($patientId, $examType);
        } else {
            // Patient had ticket on today, and the ticket HAS NO insurance info
            // Reuse the ticket
            $examType = EnumerationConstant::EXAMINATION_TYPE_SERVICE_KEY;
            $res = $ticketObj->getLatestTicketByDate($patientId, $examType);
        }
        
        if ($res !== false && $res['iso_date'] == $today) {
            $result['ticketId'] = $res['ticket_id'];
            $result['recordId'] = $medicalRecordObj->getRecordIdFromTicket($res['ticket_id']);
        } else {
            // Create new ticket
            $ticketObj->addNewTicket($patientId, $departmentId, EnumerationConstant::PATIENT_TYPE_OUTPATIENT);
            $ticketObj->populateArray(array('enum_examination_type' => $examType));
            $ticketObj->persist();
            $result['ticketId'] = $ticketObj->get_id();
            
            if ($examType == EnumerationConstant::EXAMINATION_TYPE_INSURANCE_KEY) {
                $insurance = Insurance::fromPatientId($patientId);
                $ti = Celini::newOrdo('TicketInsurance');
                $ti->setData($ticketObj->get_id(), $insurance->get_id(),
                                $insurance->get('correct_route'), $insurance->get('paid_for_36_month'));
                $ti->persist();
            }
            
            // Create empty medical profile if require
            if ($medicalRecordObj->getRecordIdFromTicket($ticketId) == false) {
                $recordId = $medicalRecordObj->addNewRecord($patientId, $ticketObj->get_id());
                $this->createMedicalProfile($recordId, array());
                $result['recordId'] = $recordId;
            }
        }
        return $result;
    }

    public function deletePatient($patientId) {
    	// Following information must be deleted
    	// 1. Demographic info (patient, person, adresss)
    	// 2. ticket
      	// 3. medical_record

    	// Get all rhm_payment_id by patient
    	$this->_db->BeginTrans();
    	try {
    	    // TODO ptnguyen 2010-04-05
            // Delete patient including
            //   encounter, prescription, ..
            //   ticket, insurance, ticket_item,...
            
            // Perform 3
            $sql	=	"DELETE FROM medical_record WHERE patient_id = '$patientId'";
            $res	=	$this->_db->execute($sql);
            if ($res === false) {
            	throw new Exception("Error in query- " . $this->_db->ErrorMsg().": $sql");
            }

            // Perform 2
            $sql	=	"DELETE FROM ticket WHERE patient_id = '$patientId'";
            $res	=	$this->_db->execute($sql);
            if ($res === false) {
            	throw new Exception("Error in query- " . $this->_db->ErrorMsg().": $sql");
            }

            // Perform 1
            $res	=	Celini::newORDO('Patient')->deletePatient($patientId);
            if ($res === false) {
            	throw new Exception("Error in query- " . $this->_db->ErrorMsg().": $sql");
            }

        } catch(Exception $ex) {
            $this->_db->RollbackTrans();
            throw $ex;
        }
        $this->_db->CommitTrans();
    }
    
    ///////////////////////// --- PRIVATE AREA --- //////////////////////////
//
    private function createMedicalProfile($recordId, $data = array()) {
         // Create default medical profile if needed
    }
   

    private function saveInsurance($registrationInfoObj, $patientId) {
        // add insurance if exists
        $insuranceData = $registrationInfoObj->getInsuranceData();
        foreach ($insuranceData as $item) {
            $objIns =   Insurance::fromPatientId($patientId);
            $item['patient_id'] = $patientId;
            
            $objIns->populateArray($item);
            $objIns->persist();
        }
    }
    
    
    
}
?>